#!flask/bin/python

from collections import Counter
import numpy as np
import gensim
import jieba
from flask import Flask, jsonify
from flask import abort
from flask import request
import settings
configs = settings.configs
app = Flask(__name__)
####model = gensim.models.word2vec.Word2Vec.load('D:\\BaiduYunDownload\\word2vec_from_weixin\\word2vec\\word2vec_wx')
model = gensim.models.word2vec.Word2Vec.load(configs["modelpath"])
# model = gensim.models.Word2Vec()
def predict_proba(oword, iword):
    iword_vec = model[iword]
    oword = model.wv.vocab[oword]
    oword_l = model.syn1[oword.point].T
    dot = np.dot(iword_vec, oword_l)
    lprob = -sum(np.logaddexp(0, -dot) + oword.code*dot) 
    return lprob

def keywords(s):
    s = [w for w in s if w in model]
    ws = {w:sum([predict_proba(u, w) for u in s]) for w in s}
    return Counter(ws).most_common()

def hotwods(s):
    w = jieba.cut(s)
    rt = keywords(w)[0:2]
    ss = [ w[0] for w in rt]
    return ss

def hotbayes(s):
    w = jieba.cut(s)
    rt = keywords(w)[0:5]
    ss = [ w[0] for w in rt]
    return ss
"""
#str = []
#str.append('太阳是一颗恒星')
#str.append('编写关于OA会议室预定管理的代码')
#str.append('编写修复几天来积累的bug')
#str.append('项目管理文档更新')

#for s in str :
#    print(hotwods(s))


#s = '太阳是一颗恒星'
#s='编写关于OA会议室管理的代码'
#print(keyWords)

"""

@app.route('/keyword/tasks', methods=['POST'])
def keyword_task():
    if not request.json or not 'text' in request.json:
        abort(400)
    task = {
        'msgid': request.json['msgid'], 
        'text': request.json['text'],
        'keywords': hotwods(request.json['text'])
    }
    #return jsonify({'res': task}), 200
    return jsonify(task), 200

@app.route('/keyword/bayes', methods=['POST'])
def keyword_task2():
    if not request.json or not 'text' in request.json:
        abort(400)
    task = {
        'msgid': request.json['msgid'], 
        'text': request.json['text'],
        'keywords': hotbayes(request.json['text'])
    }
    #return jsonify({'res': task}), 200
    return jsonify(task), 200

if __name__ == '__main__':
    app.run()